﻿package src.com.online.rpg.input
{
	import flash.display.DisplayObject;
	import flash.events.KeyboardEvent;
	
	
	/* InputManager
	 * 
	 * A class meant to replicate the behavior of AS2 Key.isDown.
	 * 
	 * Some possible improvements:
	 * Add a Key.isTapped for checking if the key has just been pressed
	 * Allow configurable controls by adding a "bindings" array
	 * Allow playback of input replays
	 * Singleton pattern
	 */ 
	public class InputManager
	{
		private static var _stage:DisplayObject;
		private static var _keys:Vector.<Boolean>;	// current key states are stored here
		
		private static const INPUT_PRIOIRTY:uint = 10;
		
		public static function initialize(stage:DisplayObject):void
		{
			// place key listeners on stage to always receieve events
			if (stage)
			{
				_stage = stage;
				_stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown, false, INPUT_PRIOIRTY, true);
				_stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp, false, INPUT_PRIOIRTY, true);
			}
			
			_keys = new Vector.<Boolean>(256, true);
		}
		
		private static function onKeyDown(e:KeyboardEvent):void
		{
			_keys[e.keyCode] = true;
		}
		
		private static function onKeyUp(e:KeyboardEvent):void
		{
			_keys[e.keyCode] = false;
		}
		
		public static function isKeyDown(key:uint):Boolean
		{
			if (key < 256) return _keys[key];
			else return false;
		}
		
		public static function dispose():void
		{
			if (_stage)
			{
				_stage.removeEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
				_stage.removeEventListener(KeyboardEvent.KEY_UP, onKeyUp);
			}
		}
	}

}